package org.jsets.fastboot.persistent.impl;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.javers.repository.sql.ConnectionProvider;

public class JaversConnectionProvider implements ConnectionProvider {

	private static final int CONNECTION_VALID_TIMEOUT = 5;// 链接有效期监测超时时间

	private final DataSource dataSource;
	private Connection current;

	public JaversConnectionProvider(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	public Connection getConnection() throws SQLException {
		if (this.isCurrentValid()) {
			return this.current;
		}

		synchronized (this) {
			if (this.isCurrentValid()) {
				return this.current;
			}
			this.current = this.dataSource.getConnection();
			return this.current;
		}
	}

	public boolean isCurrentValid() {
		if (null == this.current) {
			return false;
		}

		try {
			if (this.current.isValid(CONNECTION_VALID_TIMEOUT)) {
				return true;
			}
		} catch (SQLException e) {
			// 忽略
		}

		return false;
	}

}